<template>
  <div id="SubTitle" class="border-text subtitle perfect-scrollbar">
    <div>
      <div
        v-for="(message,index) in reallyMessage"
        :key="index"
      >
        {{message}}
      </div>
      <div>{{currentMessage}}</div>
    </div>
  </div>
</template>

<script>
import { hex_md5 as md5 } from '@/utils/secret/md5.js'
import CryptoJSNew from '@/utils/secret/HmacSHA1.js'
import CryptoJS from '@/utils/secret/hmac-sha256.js'
import '@/utils/secret/enc-base64-min.js'

export default {
  name: 'Tranfer',
  props: {
    messageList: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      recorder: null,
      mediaStream: null,
      ws: null,
      state: 'ing',
      isRecording: true,
      buffers: [],
      currentMessage: ''
    }
  },
  computed: {
    reallyMessage () {
      return this.messageList.slice(this.messageList.length - 2)
    }
  },
  watch: {
    // messageList () {
    //   this.$nextTick().then(() => {
    //     const subtitleBox = document.getElementById('SubTitle')
    //     subtitleBox.scrollTop = subtitleBox.scrollHeight
    //   })
    // }
  },
  methods: {
    init () {
      this.state = 'ing'
      // 音频转码worker
      const recorderWorker = new Worker('/js/transformpcm.worker.js')
      recorderWorker.onmessage = (e) => {
        this.buffers.push(...e.data.buffer)
      }
      navigator.mediaDevices.getUserMedia({
        audio: true,
        video: false
      }).then((stream) => {
        const audioContext = new AudioContext()
        this.mediaStream = audioContext.createMediaStreamSource(stream)
        this.recorder = audioContext.createScriptProcessor(0, 1, 1)
        this.mediaStream.connect(this.recorder)
        this.recorder.connect(audioContext.destination)
        this.recorder.onaudioprocess = event => {
          if (!this.isRecording) return
          recorderWorker.postMessage({
            command: 'transform',
            buffer: event.inputBuffer.getChannelData(0)
          })
        }
        this.connectWebsocket()
      })
    },
    getHandShakeParams () {
      var appId = '5fb3bfa6'
      var secretKey = 'f9771f02f8a5d7bb3d7c428c471820e4'
      var ts = Math.floor(new Date().getTime() / 1000)
      var signa = md5(appId + ts)
      var signatureSha = CryptoJSNew.HmacSHA1(signa, secretKey)
      var signature = CryptoJS.enc.Base64.stringify(signatureSha)
      signature = encodeURIComponent(signature)
      return '?appid=' + appId + '&ts=' + ts + '&signa=' + signature
    },
    setResult (data) {
      const rtasrResult = []
      rtasrResult[data.seg_id] = data
      rtasrResult.forEach(i => {
        let str = ''
        i.cn.st.rt.forEach(j => {
          j.ws.forEach(k => {
            k.cw.forEach(l => {
              str += l.w
            })
          })
        })
        if (i.cn.st.type === '0') {
          this.$emit('add', str)
          this.currentMessage = ''
        } else {
          this.currentMessage = str
        }
      })
    },
    connectWebsocket () {
      var url = 'wss://rtasr.xfyun.cn/v1/ws'
      var urlParam = this.getHandShakeParams()
      url = `${url}${urlParam}`
      this.ws = new WebSocket(url)
      this.ws.onopen = (e) => {
        this.wsOpened(e)
      }
      this.ws.onmessage = (e) => {
        const jsonData = JSON.parse(e.data)
        if (jsonData.action === 'started') {
          // 握手成功
          console.log('握手成功')
        } else if (jsonData.action === 'result') {
          // 转写结果
          this.setResult(JSON.parse(jsonData.data))
        } else if (jsonData.action === 'error') {
          // 连接发生错误
          console.log('出错了:', jsonData)
        }
      }
      this.ws.onclose = (e) => {
        console.log('断开连接')
      }
    },
    wsOpened () {
      if (this.ws.readyState !== 1) {
        return
      }
      var audioData = this.buffers.splice(0, 12800)
      this.ws.send(new Int8Array(audioData))
      this.handlerInterval = setInterval(() => {
        // websocket未连接
        if (this.ws.readyState !== 1) {
          clearInterval(this.handlerInterval)
          return
        }
        if (this.buffers.length === 0) {
          if (this.state === 'end') {
            this.ws.send('{"end": true}')
            console.log('发送结束标识')
            clearInterval(this.handlerInterval)
          }
          return false
        }
        var audioData = this.buffers.splice(0, 12800)
        if (audioData.length > 0) {
          this.ws.send(new Int8Array(audioData))
        }
      }, 40)
    },
    stop () {
      this.state = 'end'
      this.mediaStream.disconnect(this.recorder)
      this.recorder.disconnect()
    },
    handleTransfer () {
      this.init()
    }
  }
}
</script>

<style lang="scss" scoped>
.subtitle {
  height: 100%;
  overflow-y: scroll;
  font-size: 25px;
  font-weight: bold;
  color: $red;
}
</style>
